/*
 * @Author: your name
 * @Date: 2021-05-25 11:24:34
 * @LastEditTime: 2021-05-31 22:01:17
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \遵义报名\zunyi\src\utils\request.js
 */
import axios from "axios"
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from "@/router/index.js"
import { Loading } from "element-ui"//引入loading

Vue.use(ElementUI);
let loadingInstance//loading实例化对象

const httpRequest = axios.create({
  baseURL: 'http://t1.ossjk.com/zyjsxy-miniapp-api/',
  timeout: 10000,
});

// 添加请求拦截器
httpRequest.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  loadingInstance = Loading.service();//显示loading效果
  let token = localStorage.getItem('zunyi_pc_token');
  if (token) {
    config.headers.jwttoken = token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
httpRequest.interceptors.response.use(function (response) {
  // 对响应数据做点什么  loading效果
  switch (response.data.code) {
    case 1003:
      {
        ElementUI.Message.error(response.data.msg)
        router.replace("/login")
        break;
      }
    case 1005://未登录
      {
        ElementUI.Message.error(response.data.msg)
        router.replace("/login")
        break;
      }

    case 1006://刷新token
      {
        localStorage.getItem('zunyi_pc_token', response.data.data);//替换本地缓存里面的旧的token
        let config = response.config
        config.headers.jwttoken = response.data.data//修改旧的请求头token
        return httpRequest.request(config)   //重新发送请求
      }
    default:
      break;
  }
  loadingInstance.close();//加载完毕后关闭loading
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default httpRequest